package infod

import (
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	cinfod "gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/repo/mgorepo/baser"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
)

var (
	_ cinfod.InfoOplogRepo = &infoOplogRepo{}
)

type infoOplogRepo struct {
	baser.BaseRepo
}

func (r *infoOplogRepo) parseSearch(is cinfod.InfoOplogSearch) bson.M {
	query := bson.M{}

	if is.InfoID != "" {
		query["infoID"] = is.InfoID
	}
	return query
}

// 分页获取信息列表：根据唯一标识获取下一页指定数量的信息实体集合
// total 总数量
func (r *infoOplogRepo) QueryPage(ctx ddd.Context, is cinfod.InfoOplogSearch, pi common.PageInfo) (npi common.PageResult, result []cinfod.InfoOplogAggregate, err error) {
	query := r.parseSearch(is)
	var cs []collInfoOpLog
	npi, err = r.DBQueryPage(ctx, collNameInfoOpLog, pi, "_id", query, nil, nil, &cs)
	if err != nil {
		if err == mgo.ErrNotFound {
			err = nil
			npi.End = 1
			return
		}
		err = errors.Wrapf(err, "查询信息失败。查询条件:%v 。分页信息:%v", is, pi)
		return
	}
	if len(cs) == 0 {
		npi.End = 1
		return
	}
	result = make([]cinfod.InfoOplogAggregate, 0, len(cs))
	for _, c := range cs {
		ia := c.ToInfoOplogAggregate()
		// 初始化聚合
		ia.Init(ia, r.AggregateRoot(), c.ID)
		result = append(result, *ia)
	}
	return
}
